const { Order, OrderItem } = require("../models/order");
const { Good, Sku } = require("../models/good");
const { Address } = require("../models/appUser");

// 创建订单
createOrder = async (req, res) => {
  try {
    const { addressId, items } = req.body;
    const appUserId = req.userId;
    // 订单编号通过时间戳生成,并且取后10位
    const orderNo = Date.now().toString().slice(-10);
    // items 是一个数组，包含了订单中的商品信息 orderId goodId skuId quantity
    // 查询总价
    let totalPrice = 0;
    let orderItems = [];
    items.forEach(async (item) => {
      const skuId = item.skuId;
      const quantity = item.quantity;
      let skuData = await Sku.findOne({
        where: { id: skuId },
      });
      totalPrice += skuData.amount * quantity;
      orderItems.push({
        goodId: skuData.goodId,
        skuId: skuId,
        quantity: quantity,
        price: skuData.amount,
      });
    });

    const order = await Order.create({
      orderNo,
      appUserId,
      addressId,
      totalPrice,
      status: "待支付",
      delivery: "",
    });

    let newOrderItems = orderItems.map((item) => {
      return {
        orderId: order.id,
        goodId: item.goodId,
        skuId: item.skuId,
        quantity: item.quantity,
        price: item.price,
      };
    });

    await OrderItem.bulkCreate(newOrderItems);

    res.status(200).json({
      code: 200,
      message: "Order created successfully",
      data: order,
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 获取所有订单
getAllOrders = async (req, res) => {
  try {
    let orders = await Order.findAll({
      include: [
        {
          model: OrderItem,
          include: {
            all: true,
          },
        },
      ],
    });
    // 查询地址信息
    orders = JSON.parse(JSON.stringify(orders));
    for (let i = 0; i < orders.length; i++) {
      const address = await Address.findOne({
        where: { id: orders[i].addressId },
      });
      orders[i].address = address;
    }
    res.status(200).json({
      orders: orders,
      code: 200,
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 根据ID获取订单
getOrderById = async (req, res) => {
  try {
    const order = await Order.findOne({
      where: { id: req.params.id },
      include: [
        {
          model: OrderItem,
          include: [
            {
              model: Good,
              attributes: ["name", "price"],
            },
            {
              model: Sku,
              attributes: ["name", "amount", "stock_quantity"],
            },
          ],
        },
      ],
    });
    // 查询地址信息
    const address = await Address.findOne({
      where: { id: order.addressId },
    });
    if (order) {
      res.status(200).json({
        order: order,
        code: 200,
        address: address,
      });
    } else {
      res.status(404).json({ error: "Order not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 修改订单状态 支付假设支付成功
changeOrderStatus = async (req, res) => {
  const appUserId = req.userId;
  const { id } = req.params;
  try {
    const order = await Order.findOne({
      where: {
        id: id,
        appUserId: appUserId,
      },
    });
    if (order) {
      await order.update({ status: "待发货" });
      res.status(200).json({
        message: "Order status updated successfully",
        data: order,
        code: 200,
      });
    } else {
      res.status(404).json({ error: "Order not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 根据id查询sku
getSkuById = async (req, res) => {
  try {
    const sku = await Sku.findOne({
      where: { id: req.params.id },
    });
    if (sku) {
      res.status(200).json(sku);
    } else {
      res.status(404).json({ error: "Sku not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 订单发货
shipOrder = async (req, res) => {
  const { id } = req.params;
  const { delivery } = req.body;
  try {
    const order = await Order.findOne({
      where: {
        id: parseInt(id),
      },
    });

    if (order) {
      await order.update({
        status: "已发货",
        delivery: delivery,
      });
      res.status(200).json({
        message: "Order status updated successfully",
        data: order,
        code: 200,
      });
    } else {
      res.status(400).json({ error: "Order not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 完成订单
finishOrder = async (req, res) => {
  const { id } = req.params;
  try {
    const order = await Order.findOne({
      where: {
        id: parseInt(id),
      },
    });

    if (order) {
      await order.update({
        status: "已完成",
      });
      res.status(200).json({
        message: "Order status updated successfully",
        data: order,
        code: 200,
      });
    } else {
      res.status(400).json({ error: "Order not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

module.exports = {
  createOrder,
  getAllOrders,
  getOrderById,
  changeOrderStatus,
  shipOrder,
  finishOrder
};
